package com.txzt.gaea.provide.service.biz;

import com.txzt.base.core.RtnInfo;
import com.txzt.gaea.api.client.AdminRemoteService;
import com.txzt.gaea.dto.DeptDTO;
import com.txzt.gaea.vo.ZTreeNodeVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class DeptApiService {

    @Value("${tool.code}")
    String toolCode;
    @Value("${tool.version}")
    String toolVersion;

    @Autowired
    private AdminRemoteService adminRemoteService;

    public List<ZTreeNodeVO> deptInfoList(){
        DeptDTO var1 = new DeptDTO();
        var1.setToolCode(toolCode);
        var1.setToolVersion(toolVersion);
        var1.setParentNodeId(0L);
        RtnInfo<List<ZTreeNodeVO>> result = adminRemoteService.getDeptTree(var1);
        if (result == null) {
            return null;
        }
        List<ZTreeNodeVO> list = result.getData();
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<ZTreeNodeVO> deptList = new ArrayList<>();
        for (ZTreeNodeVO z : list) {
            if (StringUtils.equals(z.getId(), "0")) {
                continue;
            }
            if (z.getIsParent()) {
                getChildNode(z,deptList);
            }
            deptList.add(z);
        }
        return deptList;
    }
    private void getChildNode(ZTreeNodeVO node,List<ZTreeNodeVO> deptList){
        List<ZTreeNodeVO> childList = new ArrayList<>();
        if (node.getIsParent()){
            //查询子集
            DeptDTO var1 = new DeptDTO();
            var1.setToolCode(toolCode);
            var1.setToolVersion(toolVersion);
            var1.setParentNodeId(Long.parseLong(node.getId()));
            RtnInfo<List<ZTreeNodeVO>> result = adminRemoteService.getDeptTree(var1);
            if (result == null) {
                return;
            }
            List<ZTreeNodeVO> list = result.getData();
            if (CollectionUtils.isEmpty(list)) {
                return;
            }
            childList.addAll(list);
        }
        if (!CollectionUtils.isEmpty(childList)){
            for (ZTreeNodeVO item : childList) {
                if (item.getIsParent()){
                    getChildNode(item,deptList);
                }
            }
        }
        deptList.addAll(childList);
    }
}
